package org.grew.openEntity.service.Impl;

import org.grew.openEntity.repository.ColumnRepository;
import org.grew.openEntity.repository.EntityColumnRepository;
import org.grew.openEntity.po.logic.ColumnObj;
import org.grew.openEntity.po.logic.EntityColumnObj;
import org.grew.openEntity.service.ColumnService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;
import java.util.Optional;

/**
 * @program: open_entity
 * @author: todd
 * @create: 2019-01-05 22:39
 * @description: ${description}
 */
@Service
@Transactional
public class ColumnServiceImpl implements ColumnService {

    @Autowired
    private ColumnRepository columnRepository;

    @Autowired
    private EntityColumnRepository entityColumnRepository;

    @Override
    public void createColumn(ColumnObj column, Long entityId) {
        ColumnObj result = columnRepository.save(column);
        entityColumnRepository.save(new EntityColumnObj(entityId, result.getId()));
    }

    @Override
    public void updateColumn(ColumnObj column, Long entityId) {
        ColumnObj result = columnRepository.save(column);
        entityColumnRepository.save(new EntityColumnObj(entityId, result.getId()));
    }

    @Override
    public void deleteColumn(Long id) {
        columnRepository.deleteById(id);
    }

    @Override
    public ColumnObj getColumnById(Long id) {
        Optional<ColumnObj> byId = columnRepository.findById(id);
        return byId.isPresent() ? byId.get() : null;
    }

    @Override
    public List<ColumnObj> getColumnByName(String columnName) {
        return columnRepository.findColumnObjByColumnName(columnName);
    }

    @Override
    public long getColumnCount() {
        return columnRepository.count();
    }
}
